/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package user;

import java.io.*;
import java.util.*;
import java.util.logging.*;

class Contact implements Serializable {

    private String name_;

    /**
     * Creates clear contact.
     */
    public Contact() {}

    /**
     * Creates contact with specifed name and IP.
     * @param name
     * @param IP
     */
    public Contact(String name) {
        name_ = name;
    }

    /**
     * Setter.
     * @param name
     */
    public void setName(String name) {
        name_ = name;
    }

    /**
     * Getter.
     * @return
     */
    public String getName() {
        return name_;
    }
}


class Comparator implements java.util.Comparator<String>, Serializable {

    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);

    }

}
/**
 *
 * @author Paweł
 */
public class Contacts {
    private static final String FILENAME = "contacts.dat";

    private java.util.TreeMap<String, Contact> contacts;

    /**
     * Tries to load contacts form contacts.dat if unable, then creates new clean list of contacts.
     */
    public Contacts() {
        try {
            contacts = (TreeMap<String, Contact>) new ObjectInputStream(new FileInputStream(FILENAME)).readObject();
        } catch (Exception ex) {
            contacts = new TreeMap<String, Contact>(new Comparator());
        }
    }

    /**
     * Saves contact list in contacts.dat file.
     */
    public void save() {
        try {
           new ObjectOutputStream(new FileOutputStream(FILENAME)).writeObject(contacts);
           // javax.xml.bind.JAXB.marshal(contacts, new FileOutputStream(FILENAME));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Contacts.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Contacts.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Adds new contact.
     * @param name
     * @param IP
     */
    public void add(String name) {
        contacts.put(name, new Contact(name));
    }

    /**
     * Removes contact with specified username.
     * @param name
     */
    public void remove(String name) {
       contacts.remove(name);
    }

    /**
     * Retruns collection of contact names.
     * @return
     */
    public Collection<String> values() {
        Iterator<Contact> iter = contacts.values().iterator();
        Collection<String> names = new Vector<String>();
        while (iter.hasNext()) { names.add(iter.next().getName()); }
        return names;
    }
}
